import { Injectable } from '@angular/core';
import { LogService, OperationType } from '../log/services/log.service';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root',
})
export class HistoryService {
  constructor(private http: HttpClient, private logService: LogService) {}

  async log_web(option: { target_type: LogWebTarget; target_id?: number; area_id?: number }) {
    if (!option.target_id) {
      delete option.target_id;
    } else {
      if (option.target_type === LogWebTarget.Area) {
        const zoneResourceLog = await this.webHistoryLog({ area_id: option.target_id });
        const zoneLog = await this.webHistoryLog(option);
        const arr = [...zoneLog, ...zoneResourceLog]
          .map(log => {
            log.created_at = new Date(log.created_at);
            return log;
          })
          .sort((a, b) => b.created_at.getTime() - a.created_at.getTime());
        // disctinct
        const uniqueArr = arr.filter((value, index, self) => {
          return self.map(x => x.id).indexOf(value.id) == index
        })
        return uniqueArr.slice(0, 10);
      }
    }
    return this.webHistoryLog(option);
  }
  webHistoryLog(params: any) {
    return this.http.get<WebHistoryLog[]>('/api/admin/logs/web/operation', { params }).toPromise();
  }
}

export enum LogWebTarget {
  Area = 2000,
  Human,
  Pc,
  Software,
}
export const TypeToTarget = {
  zone: LogWebTarget.Area,
  personnel: LogWebTarget.Human,
  computer: LogWebTarget.Pc,
  software: LogWebTarget.Software,
};

interface WebHistoryLog {
  id: number;
  target_id: number;
  uid: number;
  operator: string;
  full_name: string;
  content: string;
  target_desc: string;
  target_name: string;
  operation_desc: string;
  target_type: number;
  operation: number;
  created_at: Date;
  area_name: string;
}
